import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild, ViewEncapsulation } from '@angular/core';
import { AppConsts } from '@shared/AppConsts';
import { AppComponentBase } from '@shared/common/app-component-base';
import { OrganizationUnitDto, ProfileServiceProxy, TaskForModelDto, TaskServiceProxy, OutsourcingWorkFlowServiceProxy, UserServiceProxy, OutsourcingDto, OutsourcingWorkFlowStepUserDto, OutsourcingWorkFlowInputDto, OutsourcingFormInputDto, SupplierServiceProxy, OutsouringServiceProxy } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap';
import { IOrganizationUnitsTreeComponentData, OrganizationUnitsTreeComponent } from '../shared/organization-unit-tree.component';
import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';
import { TaskService } from '../task/Task.service';

import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { SelectItem, SelectItemGroup } from 'primeng/api';
@Component({
  selector: 'flowapplyCrucialCreate',
  templateUrl: './flowapplyCrucialCreate.component.html',
  styleUrls: ['./flowapplyCrucialCreate.component.css']
})
export class FlowapplyCrucialCreateComponent extends AppComponentBase {
  @ViewChild('createOrEditModal') modal: ModalDirective;
  @ViewChild('paginator') paginator: Paginator;
  @ViewChild('taskdataTable') taskdataTable: Table;
  @ViewChild('dataTable') dataTable: Table;


  @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
  filterText = '';
  active = false;
  saving = false;
  selectedCar3: string;
  task: TaskForModelDto = new TaskForModelDto();
  Outsourcings;
  supplierUnits = [];
  SupplierAyy: SelectItem[];
  users: SelectItemGroup[];
  stepusers: OutsourcingWorkFlowStepUserDto;
  workflow: OutsourcingWorkFlowInputDto = new OutsourcingWorkFlowInputDto();
  clonedOutsourcings: { [s: number]: OutsourcingDto; } = {};
  constructor(injector: Injector,
    private _taskServiceProxy: TaskServiceProxy,
    private _outSourcingworkflowServiceProxy: OutsourcingWorkFlowServiceProxy,
    private _taskService: TaskService,
    private _supplierService: SupplierServiceProxy,
    private _outSourcingServiceProxy: OutsouringServiceProxy,
    private _userService: UserServiceProxy,
    private _profileService: ProfileServiceProxy) {
    super(injector);
  }

  show(taskId?: number): void {
    this.active = true;
    this._taskService.clearOutSourcs();
    this._outSourcingworkflowServiceProxy.buildWorkFlowCode().subscribe(flowcode => {
      this.workflow.code = flowcode;
      this.modal.show();
    });
  }
  // tslint:disable-next-line: use-life-cycle-interface
  ngOnInit(): void {

    this.Outsourcings =  [];
    this.workflow = new OutsourcingWorkFlowInputDto();
    this._supplierService.getAllSupplierItems().subscribe(resultdata => {
      this.SupplierAyy = resultdata;
    });
    this._userService.getAllUserForDropDown().subscribe(resultdata => {
      console.log(resultdata);
      this.users = resultdata;
    });
    this.stepusers = new OutsourcingWorkFlowStepUserDto();
  }
  onShown(): void {
    //document.getElementById('Code').focus();
  }

  joinTask(task) {
    let outsourcing = this.Outsourcings.filter(x => x.taskForModelId === task.id)[0];

    if (outsourcing === undefined) {
      console.log(outsourcing);
      let _dto = new OutsourcingDto();
      _dto.taskForModelId = task.id;
      _dto.picNo = task.picNo;
      _dto.taskCode = task.code;
      _dto.taskName = task.displayName;
      _dto.taskCount = task.amount;
      _dto.outsouringAmount = 0;
      _dto.deliveryRate = null;
      _dto.workStatus = '';
      _dto.unitPrice = 0;
      this.Outsourcings.push(_dto);
    } else {
      this.notify.info('该任务已经在申请列表中！');
    }
  }

  save(): void {
    let input = new OutsourcingFormInputDto();
    input.outSourcingDtos = this.Outsourcings;
    input.workFlowDto = this.workflow;
    input.workFlowDto.supplierUnit = this.supplierUnits.toString();
    input.stepUserDto = this.stepusers;
    this.saving = true;
    //判断审批用户是否设置
    console.log(this.stepusers);
    if (!this.stepusers.workshopManager) {
      this.notify.info('请选择单位经办人');
      this.saving = false;
      return;
    }
    if (!this.stepusers.workShopLeader) {
      this.notify.info('请选择单位主管领导');
      this.saving = false;
      return;
    }
    if (!this.stepusers.plannedProductionModelManager) {
      this.notify.info('计划生产处型号主管');
      this.saving = false;
      return;
    }
    if (!this.stepusers.plannedProductionLeader) {
      this.notify.info('计划生产处主管处长');
      this.saving = false;
      return;
    }

    if (!this.stepusers.qualityDepartmentLeader) {
      this.notify.info('质量处主管处长');
      this.saving = false;
      return;
    }
    if (!this.stepusers.technicalManager) {
      this.notify.info('工艺处主管处长');
      this.saving = false;
      return;
    }
    if (!this.stepusers.plannedProductionDirector) {
      this.notify.info('计划生产处处长');
      this.saving = false;
      return;
    }
    if (!this.stepusers.chiefEngineer) {
      this.notify.info('副总指挥(副总工程师)');
      this.saving = false;
      return;
    }
    if (!this.stepusers.customerRepresentative) {
      this.notify.info('顾客代表');
      this.saving = false;
      return;
    }
    if (!this.stepusers.companyLeader) {
      this.notify.info('公司领导');
      this.saving = false;
      return;
    }
    console.log(input);
    this._outSourcingworkflowServiceProxy.createOrUpdateCrucialWorkFlow(input)
      .pipe(finalize(() => { this.saving = false; }))
      .subscribe(() => {
        this.notify.info(this.l('SavedSuccessfully'));
        this.close();
        this.modalSave.emit(null);
      });
  }
  onRowEditInit(task: OutsourcingDto) {
    console.log(task);
    this.clonedOutsourcings[task.taskForModelId.toString()] = { ...task };
  }
  onRowEditSave(task: OutsourcingDto) {
    if (task.outsouringAmount > 0) {
      delete this.clonedOutsourcings[task.taskForModelId.toString()];
      this.notify.info(this.l('SavedSuccessfully'));
    } else {
      this.notify.info('申请数量不能小于0');
    }
  }
  onRowEditCancel(task: OutsourcingDto, index: number) {
    console.log(this.clonedOutsourcings[task.taskForModelId.toString()]);
    this.Outsourcings[index] = this.clonedOutsourcings[task.taskForModelId.toString()];
    delete this.Outsourcings[task.taskForModelId];
  }
  close(): void {
    this.active = false;
    this.modal.hide();
  }

  getTasks(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }
    this.primengTableHelper.showLoadingIndicator();
    this._taskServiceProxy.getTaskForModel(
      this.filterText,
      //this.primengTableHelper.getSorting(this.dataTable),
      'code',
      this.primengTableHelper.getMaxResultCount(this.paginator, event),
      this.primengTableHelper.getSkipCount(this.paginator, event),
    ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(result => {
      console.log('4444');
      this.primengTableHelper.totalRecordsCount = result.totalCount;
      this.primengTableHelper.records = result.items;
      this.primengTableHelper.hideLoadingIndicator();
    });
  }

  getOutsourcing(event?: LazyLoadEvent) {
    this.Outsourcings = this._taskService.getOutSourcings();
  }
  deleteRow(): void {

  }
}
